package com.sgb.kjwl.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.sgb.alimaplibrary.MapLocationTools;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.model.entity.DriverTrailInfo;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.LocationUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.util.MLog;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 实时定位service
 */
public class LocationService extends Service {

    private DriverTrailInfo mPushInfo;
    private MapLocationTools mMapLocationTools;
    //定位信息广播监听
    private LocationBroadcast mLocationBroadcast;
    /**
     * 防止开关定位服务开关时是广播连续回调
     */
    private final int HANDLER_TAG = 1;
    private final long DELAYED_TIME = 1000L;
    private Handler mHandler = new Handler(msg -> {
        if (msg.what == HANDLER_TAG) {
            MLog.d("api定位", "resetLocation");
            startLocation();
        }
        return false;
    });
    boolean isFristLocation = true;

    @Override
    public void onCreate() {
        super.onCreate();
        mPushInfo = new DriverTrailInfo();
        mPushInfo.setUserNo(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, ""));
        //初始化定位
        initLocation();
        //监听定位信息开关
        initReceiver();
        //开始定位
        startLocation();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    private void initReceiver() {
        if (mLocationBroadcast == null) {
            mLocationBroadcast = new LocationBroadcast();
            //监听定位开关
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
            registerReceiver(mLocationBroadcast, filter);
        }
    }

    /**
     * 开始定位
     */
    private void initLocation() {
        if (mMapLocationTools != null) return;
        mMapLocationTools = new MapLocationTools(getApplicationContext());
        mMapLocationTools.initLocation(true);
        mMapLocationTools.setLoctionDetailListener((aMapLocation) -> {
            mPushInfo.setLatitude(aMapLocation.getLatitude());
            mPushInfo.setLongitude(aMapLocation.getLongitude());
            mPushInfo.setProvinceName(aMapLocation.getProvince());
            mPushInfo.setCityName(aMapLocation.getCity());
            mPushInfo.setDistrictName(aMapLocation.getDistrict());
            mPushInfo.setDetailAddress(aMapLocation.getAddress());
            mPushInfo.setTime(System.currentTimeMillis());

            saveData(aMapLocation);

            MLog.d("api定位", aMapLocation.getAddress() + "-" + aMapLocation.getLatitude() + "~" + aMapLocation.getLongitude());
            if (UserOperating.getInstance().isLogged()
                    && UserOperating.getInstance().isAuthDriver()
                    && UserOperating.getInstance().getUserInfo() != null
                    && UserOperating.getInstance().getUserInfo().isHasCar()) {
                //查找省市区code
                AddressEntity[] code = AddressHelper.getInstance().findCode(aMapLocation.getProvince(), aMapLocation.getCity(), aMapLocation.getDistrict());
                if (code != null && code.length >= 3) {
                    mPushInfo.setProvinceNo(code[0] != null ? code[0].getNo() : "");
                    mPushInfo.setCityNo(code[1] != null ? code[1].getNo() : "");
                    mPushInfo.setDistrictNo(code[2] != null ? code[2].getNo() : "");

                }
                saveLocation();
            }
        });
    }

    private void saveData(AMapLocation aMapLocation) {
        //将经纬度保存到本地
        if ("4.9E-324".equals(String.valueOf(aMapLocation.getLongitude()))) {
            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LONGITUDE_ID, "");
            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LATITUDE_ID, "");
            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LONGITUDE, "");
            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LATITUDE, "");
        } else {
            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LONGITUDE_ID, String.valueOf(aMapLocation.getLongitude()));
            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LATITUDE_ID, String.valueOf(aMapLocation.getLatitude()));
            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.PROVINCE_ID, String.valueOf(aMapLocation.getAddress()));
            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LONGITUDE, String.valueOf(aMapLocation.getLongitude()));
            SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LATITUDE, String.valueOf(aMapLocation.getLatitude()));
            if (isFristLocation) {
                isFristLocation = false;
                EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_LOGISTICS_REFRESH));
            }
        }
        //保存定位省市区
        if(!TextUtils.isEmpty(aMapLocation.getCity())) {
            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.Province, !aMapLocation.getProvince().equals("") ? aMapLocation.getProvince() : "新疆维吾尔自治区");
            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.City, !aMapLocation.getCity().equals("") ? aMapLocation.getCity() : "乌鲁木齐");
            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.adCode, !aMapLocation.getAdCode().equals("") ? aMapLocation.getAdCode() : "650000");
            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.Area, !aMapLocation.getDistrict().equals("") ? aMapLocation.getDistrict() : "天山");
            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.AoiName, !aMapLocation.getDistrict().equals("") ? aMapLocation.getAoiName() : "");
            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.Address, !aMapLocation.getAddress().equals("") ? aMapLocation.getStreet() : "");
        }
    }

    public void saveLocation() {
        APIManager.getInstance().getDriverAPI().saveDriverTrail(mPushInfo).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    MLog.d("saveLocation", "轨迹上传成功");
                } else {
                    MLog.d("saveLocation", "轨迹上传失败");
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {

            }
        });
    }

    private void startLocation() {
        if (mMapLocationTools != null) {
            mMapLocationTools.startLocation();
        }
    }

    private void stopLocation() {
        if (mMapLocationTools != null) {
            mMapLocationTools.stopLocation();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MLog.d("定位", "onDestroy");
        if (mMapLocationTools != null) {
            mMapLocationTools.destroy();
            mMapLocationTools = null;
        }
        if (mLocationBroadcast != null) {
            unregisterReceiver(mLocationBroadcast);
            mLocationBroadcast = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 监听定位广播
     */
    private class LocationBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //定位信息开关打开时重新定位
            if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())
                    && LocationUtil.isOpenLocation(context)) {
                //防止重复调用
                mHandler.removeMessages(HANDLER_TAG);
                mHandler.sendEmptyMessageDelayed(HANDLER_TAG, DELAYED_TIME);
            }
            //监听手机亮屏与息屏，暂停与重启定位服务
            if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
                MLog.d("定位", "ACTION_SCREEN_ON - 亮屏");
                startLocation();
            }
            if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
                MLog.d("定位", "ACTION_SCREEN_OFF - 息屏");
                stopLocation();
            }
        }
    }
}
